<template>
	<div>

		<van-nav-bar left-arrow @click-left="$router.back()" style="background-color:  #07c160;">

			<template #title>
				<span style="color: #fff; font-size: 140%;">个人信息</span>
			</template>
		</van-nav-bar>

		<div class="middle">
			<van-cell-group>
				<input type="file" hidden accept="image/*" ref="file" />

				<van-cell title="头像" center style="position: relative;">
					<van-image width="50" height="50" round fit="cover" :src="avatar" />
					<input type="file" class="upload" accept="image/*" ref="file" @change="upload" />
				</van-cell>
				<!-- 昵称 -->
				<van-cell title="昵称" is-link :value="userInfo.nickname||'请设置昵称'" @click="getNickname=true" />
				<van-dialog v-model="getNickname" title="修改昵称" show-cancel-button>
					<van-cell-group>
						<van-field v-model="userInfo.nickname" placeholder="请输入昵称" />
					</van-cell-group>
				</van-dialog>
				<!-- 性别 -->
				<van-cell title="性别" is-link :value="userInfo.sex||'请设置'" @click="sexShowPicker=true" />
				<van-popup v-model="sexShowPicker" round position="bottom">
					<van-picker show-toolbar :columns="sexColumns" @cancel="sexShowPicker = false"
						@confirm="sexOnConfirm" />
				</van-popup>
				<!-- 生日 -->
				<van-cell title="生日" is-link :value="userInfo.birthday||'请选择'" @click="birthdayShowpick=true" />
				<!-- //弹出层 -->
				<van-popup v-model="birthdayShowpick" round position="bottom">
					<van-datetime-picker v-model="currentDate" @cancel="birthdayShowpick = false"
						@confirm="birthdayOnConfirm" type="date" title="选择年月日" :min-date="minDate"
						:max-date="maxDate" />
				</van-popup>

			</van-cell-group>
			<div style="margin: 30px 50px;">
				<van-button round block type="primary" size="normal" :square="true" @click="submit">确定</van-button>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		formaDate
	} from "@/utils/helper.js"
	export default {
		name: "userInfo",
		data() {
			return {
				userInfo: {},
				getNickname: false, // 弹出框昵称
				sexShowPicker: false, //性别弹出层
				sexColumns: ['男', '女'],
				birthdayShowpick: false, //生日弹出
				minDate: new Date(1900, 0, 1),
				maxDate: new Date(),
				currentDate: new Date(2021, 0, 17),
				avatar: '', //储存头像
				file: null, //上传头像的文件
			};
		},
		computed: {
			uid() {
				return this.$store.state.uid
			}
		},
		watch: {
			//刷新 用户数据返回我们监听
			// uid(new_val,old_val){
			// 	if(new_val){
			// 		this.userInfo = JSON.parse(JSON.stringify(this.$store.state.userInfo));

			// 	}
			// },
			uid: {
				handler(new_val, old_val) {
					if (new_val) {

						let userInfo = JSON.parse(JSON.stringify(this.$store.state.userInfo));

						this.userInfo = {
							...userInfo
							// avatar,
							// sex,
							// nickname,
							// birthday
						};
						let birthday = this.userInfo.userInfo;
						if (birthday) {
							this.currentDate = new Data(birthday)
						}
						this.avatar = this.userInfo.avatar;
					}

				},
				immediate: true
			}
		},
		created() {
			// this.userInfo = this.$store.state.userInfo; //污染

			// this.userInfo = JSON.parse(JSON.stringify(this.$store.state.userInfo));
		},
		methods: {
			//生日
			birthdayOnConfirm(e) {
				console.log(e); //日期的
				console.log(formaDate(e))

				this.userInfo.birthday = formaDate(e);
				this.birthdayShowpick = false
			},



			sexOnConfirm(e) {
				console.log(e)
				this.userInfo.sex = e;
				this.sexShowPicker = false
			},
			//选图片
			upload(e) {

				let file = e.target.files[0];

				console.log(file)

				this.file = file;
				// //预览图片

				this.avatar = window.URL.createObjectURL(file);
				console.log(window.URL.createObjectURL(file))
			},

			async qnUpload(file) {

				// let file =  this.fileList[index].file;//   
				let {
					type
				} = file; // 假设只有一张图 
				//  拿到类型  比如jpg
				type = type.split('/')[1];
				// 重新命名
				let file_name = `${new Date(
						).getTime()}_${Math.random()
					.toString(36)
					.slice(2)}.${type}`;
				// 去自己的服务器拿到上传七牛云需要的 token  为何放在服务端呢?  主要是为了安全，因为里边包含了一些账号信息
				let {
					token
				} = await this.$http.post('/upload/token');
				// new一个form data   并且把文件 token  和文件的名字放进去  file token key是固定的 不能改 
				const formdata = new FormData();
				formdata.append('file', file);
				formdata.append('token', token);
				formdata.append('key', file_name);

				// https://upload-z1.qiniup.com 是上传到七牛的真正接口  其中z1是华北区域

				let result = await this.$http.post('https://upload-z1.qiniup.com', formdata);
				console.log(result);
				console.log(`http://toutiao.longxiaokj.com/` + result.key);

				// `http://toutiao.longxiaokj.com/` + result.key  这个地址就是传到服务器的地址  
				// 发布文章时 imageSrc  字段需要的就是这个
				return `http://toutiao.longxiaokj.com/` + result.key
			},

			async submit() {

				if (this.file) {
					
					this.$toast.loading({
						  duration: 200, // 持续展示 toast
						  message: '提交中...',
						  forbidClick: true,
					})
					
					let qn_res = await this.$store.dispatch('qnUplaod', this.file);
					// console.log(qn_res)
					this.userInfo.avatar = qn_res

				}
				console.log(this.userInfo)
				let {uid} = this;
				// this.userInfo.avatar
				this.$http.post('/user/editUserInfo', {
					uid,
					...this.userInfo
				}).then(res => {
					
					console.log(res);
					
					if (res.code == 0) {
						this.$toast.success(res. msg);
						//服务器拿
						// let token = this.$store.state.TOKEN;
						// this.$store.dispatch('GET_USERINFO',token);
						// {
							
						// 	avatar,
						// 	sex,
						// 	nickname,
						// 	birthday
						// }
						let  _userInfo = this.$store.state.userInfo;
						
						this.$store.commit('SET_DATA',{
							key:"userInfo",
							value:Object.assign(_userInfo,this.userInfo)
						})
						

						setTimeout(v => {
							this.$router.back()
						}, 500)
					} else {
						this.$toast(res.msg)
					}
				})
			}
		}
	}
</script>

<style scoped="scoped">
	/deep/.van-icon-arrow-left:before {
		font-size: 170%;
		color: #fff;
	}
</style>

<style lang="scss">
	.upload {
		position: absolute;
		top: 0;
		right: 0;
		width: 300px;
		height: 100px;
		z-index: 999;
		opacity: 0;
	}
</style>
